﻿-- =============================================
-- Author:		<赵洪涛>
-- Create date: <2012-08-21>
-- Description:	<OutSide获得接口人分配给自己的客户>
-- =============================================
CREATE PROCEDURE [dbo].[proc_InOutSide_GetAllotCustomer] 
(
	@UserName varchar(20),
	@StartIndex int,
	@EndIndex int
)
AS
BEGIN
	Declare @Days int,@DepartmentId int

	Set @DepartmentId = (Select DepartmentId From Employee Where UserName=@UserName)	--部门Id
	Set @Days = (Select ProtectDays From Department Where id=@DepartmentId)		--系统保护天数

	--已保护,但过了保护日期仍未签单的,自动踢入公库并且5日内不能再次被申领(根据UpTime)
	Update Customer Set ProtectId=1,ProtectName=NULL,ProtectDate=NULL,UpTime=GetDate() Where ProtectName=@UserName And DateDiff(Day,ProtectDate,GetDate())>@Days

	;WITH list As (Select ROW_NUMBER() OVER (Order by ProtectDate Desc,ProtectId ASC ,UpTime ASC) AS Row,
		A.Id,
		C.delFlag,
		C.CustomerId,
		C.CustomerName,
		C.Project,
		C.ProtectId,
		IsNull((Select Title From Customer_Source Where Id=C.SourceId),'...') As Source,
		A.InSide_ProtectDate As ProtectDate,
		IsNull((@Days-DateDiff(day,IsNull(A.InSide_ProtectDate,GetDate()),GetDate())),0) As Countdown,
		IsNull((Select Title From Customer_Industry Where Id=C.IndustryOneId),'...') As IndustryOne,
		IsNull((Select Title From Customer_Industry Where Id=C.IndustryTwoId),'...') As IndustryTwo,
		IsNull((Select Title From Customer_Type Where Id=C.TypeId),'...') As Type,
		IsNull((Select Top 1 EName From Employee Where Employee.UserName=A.InSide),'') As SalesPerson,
		A.In_Date As TrackDate
	From InOutSide A,Customer C
	Where C.ProtectName=@UserName And C.Audit=1	And A.OutSide=@UserName And A.CusId=C.CustomerId)

	Select *,(Select Count(0) From List) As RecordCount From List Where Row Between @StartIndex And @EndIndex Order By Row
END
